﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace Spencen.Mobile.Markup.Extensions
{
    public class StaticResource : IDynamicValueProvider
    {
        public StaticResource( string key )
        {
            Key = key;
        }

        public string Key { get; private set; }

        #region IDynamicValueProvider Members

        public object GetValue( XamlNode context, object parentInstance )
        {
            var parentElement = parentInstance as IResourceDictionary;
            if ( parentElement != null )
                return GetResource( parentElement, Key );
            return null;
        }

        #endregion

        private object GetResource( IResourceDictionary resourceDictionary, string keyName )
        {
            if ( resourceDictionary.Resources.ContainsKey( keyName ) )
                return resourceDictionary.Resources[ keyName ];

            if ( resourceDictionary.Parent != null )
                return GetResource( resourceDictionary.Parent, keyName );

            return null;
        }
    }
}
